// dh-banner-orphan-checker 云对象
// Banner孤立检测器

const db = uniCloud.database()
const dbCmd = db.command

module.exports = {
	/**
	 * 检测所有孤立banner
	 * 可通过定时任务或手动触发
	 */
	async checkOrphanBanners() {
		try {
			// 1. 获取所有引用类型的banner
			const bannersRes = await db.collection('dh-hospital_banners')
				.where({
					content_type: dbCmd.neq('custom')
				})
				.get()
			
			const banners = bannersRes.data || []
			
			if (banners.length === 0) {
				return {
					code: 200,
					message: '没有需要检测的banner',
					data: { total: 0, orphans: [], valid: 0 }
				}
			}
			
			// 2. 逐个检测
			const orphanBanners = []
			const validBanners = []
			
			for (const banner of banners) {
				const isValid = await this.checkBannerValidity(banner)
				
				if (!isValid.valid) {
					orphanBanners.push({
						_id: banner._id,
						title: banner.title || `引用${banner.content_type}`,
						content_type: banner.content_type,
						content_id: banner.content_id,
						reason: isValid.reason
					})
					
					// 更新banner状态
					await db.collection('dh-hospital_banners')
						.doc(banner._id)
						.update({
							is_orphan: true,
							orphan_reason: isValid.reason,
							orphan_check_time: Date.now()
						})
				} else {
					validBanners.push(banner._id)
					
					// 如果之前被标记为孤立，现在恢复了，则更新状态
					if (banner.is_orphan) {
						await db.collection('dh-hospital_banners')
							.doc(banner._id)
							.update({
								is_orphan: false,
								orphan_reason: '',
								orphan_check_time: Date.now()
							})
					}
				}
			}
			
			// 3. 如果有孤立banner，发送通知给管理员
			if (orphanBanners.length > 0) {
				await this.notifyAdmins(orphanBanners)
			}
			
			return {
				code: 200,
				message: `检测完成，发现${orphanBanners.length}个孤立banner`,
				data: {
					total: banners.length,
					orphans: orphanBanners,
					valid: validBanners.length
				}
			}
		} catch (err) {
			console.error('孤立检测失败:', err)
			return {
				code: 500,
				message: err.message || '检测失败',
				data: null
			}
		}
	},
	
	/**
	 * 检测单个banner的有效性
	 */
	async checkBannerValidity(banner) {
		let collection
		
		switch (banner.content_type) {
			case 'promotion':
				collection = 'dh-hospital_promotions'
				break
			case 'service':
				collection = 'dh-services'
				break
			case 'product':
				collection = 'dh-products'
				break
			default:
				return { valid: false, reason: '未知的内容类型' }
		}
		
		try {
			const res = await db.collection(collection)
				.doc(banner.content_id)
				.field({ _id: true, status: true })
				.get()
			
			const data = res.data?.[0]
			
			if (!data) {
				return { 
					valid: false, 
					reason: `关联的${this._getContentTypeName(banner.content_type)}不存在（ID: ${banner.content_id}）` 
				}
			}
			
			if (data.status && data.status !== 1) {
				return { 
					valid: false, 
					reason: `关联的${this._getContentTypeName(banner.content_type)}已被禁用` 
				}
			}
			
			return { valid: true, reason: '' }
		} catch (err) {
			return { valid: false, reason: `检测失败: ${err.message}` }
		}
	},
	
	/**
	 * 通知管理员
	 */
	async notifyAdmins(orphanBanners) {
		try {
			// 获取管理员列表
			const adminsRes = await db.collection('uni-id-users')
				.where({
					role: dbCmd.in(['admin', 'super_admin'])
				})
				.field({ _id: true, username: true, mobile: true })
				.limit(100)
				.get()
			
			const admins = adminsRes.data || []
			
			if (admins.length === 0) {
				console.log('没有管理员需要通知')
				return
			}
			
			// 创建通知消息
			const notificationContent = `发现 ${orphanBanners.length} 个孤立Banner需要处理：\n${
				orphanBanners.slice(0, 5).map(b => `- ${b.title || 'Banner'}: ${b.reason}`).join('\n')
			}${orphanBanners.length > 5 ? '\n...' : ''}`
			
			// 写入系统通知表（如果有的话）
			console.log('孤立Banner通知:', notificationContent)
			console.log(`需要通知 ${admins.length} 位管理员`)
			
			// TODO: 实际项目中可以集成短信/邮件/站内信通知
			
		} catch (err) {
			console.error('通知管理员失败:', err)
		}
	},
	
	/**
	 * 自动处理孤立banner
	 * @param {string} action - 'disable' 禁用 | 'delete' 删除
	 */
	async autoHandleOrphans(action = 'disable') {
		try {
			const orphansRes = await db.collection('dh-hospital_banners')
				.where({ is_orphan: true })
				.get()
			
			const orphans = orphansRes.data || []
			
			if (orphans.length === 0) {
				return { 
					code: 200, 
					message: '没有孤立banner需要处理' 
				}
			}
			
			if (action === 'disable') {
				// 批量禁用
				for (const orphan of orphans) {
					await db.collection('dh-hospital_banners')
						.doc(orphan._id)
						.update({ status: 2 })
				}
				
				return {
					code: 200,
					message: `已自动禁用 ${orphans.length} 个孤立banner`
				}
			} 
			else if (action === 'delete') {
				// 批量删除
				for (const orphan of orphans) {
					await db.collection('dh-hospital_banners')
						.doc(orphan._id)
						.remove()
				}
				
				return {
					code: 200,
					message: `已自动删除 ${orphans.length} 个孤立banner`
				}
			}
			
			return { code: 400, message: '不支持的操作类型' }
		} catch (err) {
			console.error('自动处理失败:', err)
			return { 
				code: 500, 
				message: err.message 
			}
		}
	},
	
	/**
	 * 获取孤立banner列表
	 */
	async getOrphanBanners() {
		try {
			const res = await db.collection('dh-hospital_banners')
				.where({ is_orphan: true })
				.orderBy('orphan_check_time', 'desc')
				.get()
			
			return {
				code: 200,
				message: '获取成功',
				data: res.data || []
			}
		} catch (err) {
			console.error('获取孤立banner列表失败:', err)
			return {
				code: 500,
				message: err.message || '获取失败',
				data: []
			}
		}
	},
	
	// ========== 内部辅助方法 ==========
	
	_getContentTypeName(type) {
		const typeMap = {
			promotion: '促销活动',
			service: '服务项目',
			product: '产品'
		}
		return typeMap[type] || '内容'
	}
}

